package com.design.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SingletonReflection {

	private static final SingletonReflection  singleton = new SingletonReflection();
	
	private SingletonReflection() {
		
		/**
		 * 通过在构造函数中设置检查锁，防止通过反射越权调用构造函数产生多个实例来破坏单例模式
		 */
		if(null != singleton) {
			
			throw new RuntimeException("Cannot construct a SingletonReflection more than once !");
		}
		
	}
	
	public static SingletonReflection getSingletonReflection() {
		
		return singleton;
	}
	
	
	public static void main(String[] args) {
		
		SingletonReflection singleton1 = SingletonReflection.getSingletonReflection();
		
		SingletonReflection singleton2 = SingletonReflection.getSingletonReflection();
		
		System.out.println(singleton1 == singleton2);
		
		
		try {
			
			Constructor<SingletonReflection> consSingleton = SingletonReflection.class.getDeclaredConstructor();
			//跳过权限检查，可借此反射访问私有属性与私有函数
			consSingleton.setAccessible(true);
			//可越权访问调用构造函数产生新实例，实现了破坏单例
			SingletonReflection singleton3 = consSingleton.newInstance();
			
			System.out.println(singleton1 == singleton3);
			
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
